/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my.algorithms.mcorrea;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author mcorrea
 */
public class SequenceMain {

	public static void main(String args[]){
		String input = "joe,home,joe,about,joe,career,james,home,james,cart,james,maps,mary,home,mary,about,mary,career,james1,home,james1,cart,james1,maps,james2,home,james2,cart,james2,maps";
		String inputAsArray[] = input.split(",");
		String currentUser =inputAsArray[0];
		
		List<Sequence> sequences = new ArrayList<Sequence>();
		List<String> pages = new ArrayList<String>();
		
		for(int k =1; k < inputAsArray.length; k++){	
			String page = inputAsArray[k];
			k++;
			if(k<inputAsArray.length && inputAsArray[k].equals(currentUser) ){
				pages.add(page);
			}else {
				pages.add(page);
				
				Sequence aux = findSequence(pages, sequences); 
				 if(aux!=null){
					 aux.setCount(aux.getCount()+1);
				 }else{
					 sequences.add(new Sequence(pages));
				 } 
				
				//next user
				pages = new ArrayList<String>();
				if(k<inputAsArray.length)currentUser = inputAsArray[k];
			
			}
		}
		
		Collections.sort(sequences, new Comparator<Sequence>(){
			@Override
			public int compare(Sequence o1, Sequence o2) {
				return o2.getCount() - o1.getCount();
			}
		}  );
		
		//prnting
		for(Sequence s: sequences){
			System.out.println("sequence["+s.getCount()+"]");
			for(String p: s.getSequence()){
				System.out.println(p);
			}
			
			
		}
	}
	
	
	private static Sequence findSequence(List<String> pages, List<Sequence> sequences){
	
		for(Sequence s: sequences){
			if(s.getSequence().equals(pages))return s;
		}
		return null;
	
	}
	
	
	private static class Sequence{
		private List<String> sequence ;
		private int count = 0;

		public Sequence(List<String> sequence, int count) {
			this.sequence = sequence;
			this.count = count;
		}
		public Sequence(List<String> sequence) {
			this.sequence = sequence;
			this.count++;
		}
	
		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public List<String> getSequence() {
			return sequence;
		}

		public void setSequence(List<String> sequence) {
			this.sequence = sequence;
		}
		
	}
	
	
}




